<script setup>
import { inject, onMounted, ref, shallowRef } from "vue";
import { getDownloadPage, countDownload } from "@/api/download.js";
import emitter from "@/utils/mitt.js";
import { saveAs } from "file-saver";

const getAssetsFile = inject("getAssetsFile");

const downloadList = ref([]);
const total = ref(0);
const pages = ref(0);
const queryParams = ref({
	pageSize: 10,
	pageNum: 1,
});

const getMemberList = async () => {
	const res = await getDownloadPage({ ...queryParams.value, isView: 1 });
	if (res.data.code === 200) {
		downloadList.value = res.data.data.records;
		total.value = res.data.data.total;
		pages.value = res.data.data.pages;
	}
};

onMounted(() => {
	getMemberList();
});

const splitTime = (time) => {
	// 将YYYY-MM-DD格式转换为{year: YYYY, month: MM, day: DD}
	const timestamp = Date.parse(time);
	// 如果timestamp为NaN则返回''
	if (!timestamp) return "";
	const newTime = new Date(timestamp);
	return {
		year: addZero(newTime.getFullYear()),
		month: addZero(newTime.getMonth() + 1),
		day: addZero(newTime.getDate()),
	};
};
const addZero = (num) => `${num < 10 ? "0" : ""}${num}`;

const downloadFile = (item, id) => {
	saveAs(item.accessUrl, item.originalName);
	countDownload({ id });
};
</script>

<template>
	<div class="pageContent">
		<n-list :bordered="false" hoverable style="margin-bottom: 20px">
			<n-list-item v-for="item in downloadList" style="padding: 12px 0">
				<template #prefix>
					<div class="time-box" style="text-align: center">
						<div class="time-box-day">
							{{ splitTime(item.createTime).day }}
						</div>
						<div class="time-box-yam">
							{{ splitTime(item.createTime).year + "/" + splitTime(item.createTime).month }}
						</div>
					</div>
				</template>
				<div @click="downloadFile(item.files[0], item.id)" class="titleLabel">
					{{ item.title }}
				</div>
				<div class="file-download">
					<span class="file-name">{{ item.fileName }}</span>
					<n-button text target="_blank" :color="'#c72003'" @click="downloadFile(item.files[0], item.id)">
						<template #icon>
							<n-icon :size="18" :color="'#c72003'">
								<Download />
							</n-icon>
						</template>
						下载
					</n-button>
				</div>
			</n-list-item>
		</n-list>

		<n-space justify="center">
			<n-pagination
				show-quick-jumper
				:page-count="pages"
				v-model:page-size="queryParams.pageSize"
				v-model:page="queryParams.pageNum"
				:onUpdate:page="getMemberList">
				<template #prefix>共{{ total }}条</template>
				<template #suffix>页</template>
			</n-pagination>
		</n-space>
	</div>
</template>

<style scoped>
.time-box {
	width: 70px;
	height: 70px;
	border: 1px solid var(--primary-color);
	color: var(--primary-color);
}
.time-box-day {
	height: 48px;
	font-weight: bold;
	font-size: 24px;
	border-bottom: 1px solid var(--primary-color);
	margin: auto;
	line-height: 48px;
}
.time-box-yam {
	height: 22px;
}
.file-download {
	display: flex;
	align-items: center;
}
.file-name {
	margin-right: 10px;
}
</style>
